package com.example.pplication;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class EditTaskActivity extends AppCompatActivity {
    private EditText etTitle, etDescription;
    private Spinner spPriority, spCategory;
    private Button btnDueDate, btnSave;
    private TaskManager taskManager;
    private long taskId;
    private String dueDate = "";
    private String reminderTime = "";
    private long currentUserId;
    private Calendar calendar = Calendar.getInstance();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 深色模式适配
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        boolean darkMode = prefs.getBoolean("dark_mode", false);
        AppCompatDelegate.setDefaultNightMode(
                darkMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO
        );

        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_edit_task);

            // 获取当前用户ID
            currentUserId = getCurrentUserId();
            if (currentUserId == -1) {
                Toast.makeText(this, "用户未登录，请重新登录", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                return;
            }

            // 获取任务ID
            taskId = getIntent().getLongExtra("task_id", -1);
            taskManager = new TaskManager(this, currentUserId);

            // 初始化视图
            initViews();

            // 加载任务数据
            loadTaskData();

            // 设置按钮事件
            setupButtonListeners();
        } catch (Exception e) {
            Log.e("EditTaskActivity", "初始化错误: " + e.getMessage(), e);
            Toast.makeText(this, "应用初始化失败，请重试", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        // 初始化Toolbar
        try {
            Toolbar toolbar = findViewById(R.id.toolbar);
            if (toolbar != null) {
                setSupportActionBar(toolbar);
                if (getSupportActionBar() != null) {
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setTitle(taskId == -1 ? "新建任务" : "编辑任务");
                }
            }
        } catch (Exception e) {
            Log.e("EditTask", "Toolbar error: " + e.getMessage());
        }

        // 初始化其他视图
        etTitle = findViewById(R.id.et_title);
        etDescription = findViewById(R.id.et_description);
        spPriority = findViewById(R.id.sp_priority);
        spCategory = findViewById(R.id.sp_category);
        btnDueDate = findViewById(R.id.btn_due_date);
        btnSave = findViewById(R.id.btn_save);

        // 设置优先级和分类的下拉选项
        ArrayAdapter<CharSequence> priorityAdapter = ArrayAdapter.createFromResource(this,
                R.array.priority, android.R.layout.simple_spinner_item);
        priorityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spPriority.setAdapter(priorityAdapter);

        ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource(this,
                R.array.category, android.R.layout.simple_spinner_item);
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCategory.setAdapter(categoryAdapter);

        // 确保视图不为null
        if (etTitle == null || etDescription == null || spPriority == null ||
                spCategory == null || btnDueDate == null || btnSave == null) {
            throw new RuntimeException("部分视图初始化失败");
        }
    }

    private void setupButtonListeners() {
        // 设置日期按钮事件 - 使用日期选择器
        btnDueDate.setOnClickListener(v -> showDatePickerDialog());

        // 保存按钮事件
        btnSave.setOnClickListener(v -> {
            if (saveTaskChanges()) {
                Toast.makeText(this, "任务已保存", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    private void showDatePickerDialog() {
        // 如果已有日期，解析为日历对象
        if (!dueDate.isEmpty()) {
            try {
                calendar.setTime(dateFormat.parse(dueDate));
            } catch (Exception e) {
                Log.e("EditTask", "日期解析错误: " + e.getMessage());
            }
        }

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    calendar.set(year, month, dayOfMonth);
                    dueDate = dateFormat.format(calendar.getTime());
                    btnDueDate.setText(dueDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );

        // 可选: 设置最小日期为今天
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    private void loadTaskData() {
        if (taskId != -1) {
            try (Cursor cursor = taskManager.getTaskDetails(taskId)) {
                if (cursor != null && cursor.moveToFirst()) {
                    // 安全地获取列索引
                    int titleIndex = cursor.getColumnIndex(DBHelper.COLUMN_TITLE);
                    int descIndex = cursor.getColumnIndex(DBHelper.COLUMN_DESCRIPTION);
                    int priorityIndex = cursor.getColumnIndex(DBHelper.COLUMN_PRIORITY);
                    int categoryIndex = cursor.getColumnIndex(DBHelper.COLUMN_CATEGORY);
                    int dueDateIndex = cursor.getColumnIndex(DBHelper.COLUMN_DUE_DATE);
                    int reminderIndex = cursor.getColumnIndex(DBHelper.COLUMN_REMINDER_TIME);

                    // 安全设置文本值
                    if (titleIndex >= 0) etTitle.setText(cursor.getString(titleIndex));
                    if (descIndex >= 0) etDescription.setText(cursor.getString(descIndex));
                    if (priorityIndex >= 0) setSpinnerSelection(spPriority, cursor.getString(priorityIndex));
                    if (categoryIndex >= 0) setSpinnerSelection(spCategory, cursor.getString(categoryIndex));

                    // 处理日期和提醒时间
                    if (dueDateIndex >= 0) {
                        dueDate = cursor.getString(dueDateIndex);
                        btnDueDate.setText(dueDate.isEmpty() ? "选择日期" : dueDate);
                    }

                    if (reminderIndex >= 0) {
                        reminderTime = cursor.getString(reminderIndex);
                    }
                } else {
                    Toast.makeText(this, "任务不存在或加载失败", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } catch (Exception e) {
                Log.e("EditTask", "加载任务错误: " + e.getMessage());
                Toast.makeText(this, "加载任务数据失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void setSpinnerSelection(Spinner spinner, String value) {
        if (spinner == null || value == null) return;

        for (int i = 0; i < spinner.getCount(); i++) {
            if (spinner.getItemAtPosition(i).toString().equals(value)) {
                spinner.setSelection(i);
                return;
            }
        }
    }

    private boolean saveTaskChanges() {
        // 检查用户是否已登录
        if (currentUserId == -1) {
            Toast.makeText(this, "用户未登录，请重新登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return false;
        }

        // 获取输入值
        String title = etTitle.getText().toString().trim();
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show();
            return false;
        }

        String description = etDescription.getText().toString().trim();
        String priority = spPriority.getSelectedItem().toString();
        String category = spCategory.getSelectedItem().toString();

        // 检查是否选择了日期
        if (dueDate.isEmpty()) {
            Toast.makeText(this, "请选择截止日期", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 保存任务
        if (taskId == -1) {
            long newTaskId = taskManager.addTask(title, description, priority, category, dueDate, reminderTime);
            return newTaskId != -1;
        } else {
            return taskManager.updateTask(taskId, title, description, priority, category, dueDate, reminderTime);
        }
    }

    private long getCurrentUserId() {
        try {
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            return prefs.getLong("current_user_id", -1);
        } catch (Exception e) {
            Log.e("EditTaskActivity", "获取用户ID失败: " + e.getMessage());
            return -1;
        }
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}